package com.daily.pump.http;

import android.text.TextUtils;
import android.util.Log;

import com.daily.pump.http.exception.ApiException;
import com.daily.pump.http.response.HttpResponseCode;
import com.daily.pump.model.BaseResp;
import com.daily.pump.utils.DES3Util;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xunxi.mimi.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved.
 */

public class WrapperResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private static final String TAG = WrapperResponseBodyConverter.class.getSimpleName();

    private final Type mType;

    WrapperResponseBodyConverter(Type type) {
        this.mType = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            String result = value.string();
            LogUtil.error(WrapperResponseBodyConverter.class, "Response: " + result);
            if (TextUtils.isEmpty(result)) {
                throw new ApiException(HttpResponseCode.ERROR_NETWORK_UNAVAILABLE, "网络异常，请检查网络连接");
            }

            Object object = new JSONTokener(result).nextValue();
            if (object instanceof JSONObject) {
                JSONObject data = (JSONObject) object;
                if (data.has("code") && data.has("message")) {
                    int code = data.getInt("code");
                    if (code != HttpResponseCode.SUCCESS) {
                        throw new ApiException(code, data.getString("message"));
                    }

                    if (mType.equals(BaseResp.class)) {//如果是基础类型，就直接解析
                        return new Gson().fromJson(result, mType);
                    } else {
                        if (data.has("data") && !data.isNull("data")) {
                            Object resultObj = data.opt("data");
                            if (resultObj instanceof String) {
                                result = DES3Util.decode((String) resultObj);
                            } else {
                                result = data.opt("data").toString();
                            }
                        }
                    }
                }
            }

            return new Gson().fromJson(result, mType);
        } catch (JSONException | JsonSyntaxException e) {
            LogUtil.error(WrapperResponseBodyConverter.class, Log.getStackTraceString(e));
            LogUtil.error(WrapperResponseBodyConverter.class, "type: " + mType);
            throw new ApiException(HttpResponseCode.ERROR_PARISE_FAIL, "数据解析错误");
        }
    }

}
